import path from "path";
import * as readline from "readline";
import { stdin, stdout } from "node:process";
import * as fs from "fs";
import { fileURLToPath } from "url";

const versionPath = "./public/version.json";

const rl = readline.createInterface({
  input: stdin,
  output: stdout,
});

// 版本文件存放在 src/version.json，适配uni-app多端
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const versionFile = path.join(__dirname, versionPath);

const defaultVersionInfo = {
  version: "1.0.0",
  type: "major",
  updateTime: new Date().toLocaleString("zh-CN"),
  log: ["项目发布上线"],
  historyVersion: [],
};

// 读取当前版本
const getCurrentVersion = () => {
  try {
    if (!fs.existsSync(versionFile)) {
      // 文件不存在则创建
      fs.writeFileSync(
        versionFile,
        JSON.stringify(defaultVersionInfo, null, 2)
      );
      return { ...defaultVersionInfo };
    }
    const data = fs.readFileSync(versionFile, "utf8");
    const parsed = JSON.parse(data);
    // 补全缺失字段
    return {
      version: parsed.version || "1.0.0",
      type: parsed.type || "major",
      updateTime: parsed.updateTime || new Date().toLocaleString("zh-CN"),
      log: Array.isArray(parsed.log) ? parsed.log : ["项目发布上线"],
      historyVersion: Array.isArray(parsed.historyVersion)
        ? parsed.historyVersion
        : [],
    };
  } catch (error) {
    // 解析失败也写入默认
    fs.writeFileSync(versionFile, JSON.stringify(defaultVersionInfo, null, 2));
    return { ...defaultVersionInfo };
  }
};

// 更新版本号
const updateVersion = (currentVersion, type, log) => {
  const [major, minor, patch] = currentVersion.version.split(".").map(Number);
  const typeMap = { 1: "major", 2: "feature", 3: "bugfix" };
  let newVersion;
  switch (type) {
    case "1": // 大版本
      newVersion = `${major + 1}.0.0`;
      break;
    case "2": // 新特性
      newVersion = `${major}.${minor + 1}.0`;
      break;
    case "3": // 修复bug
      newVersion = `${major}.${minor}.${patch + 1}`;
      break;
    default:
      throw new Error("无效的版本类型");
  }

  const updateTime = new Date().toLocaleString("zh-CN");
  const versionType = typeMap[type] || "unknown";

  // 构建历史版本记录
  const historyRecord = {
    version: newVersion,
    type: versionType,
    updateTime: updateTime,
    log: log,
  };

  // 将当前版本添加到历史记录中
  const historyVersion = currentVersion.historyVersion || [];
  if (currentVersion.version && currentVersion.version !== "1.0.0") {
    historyVersion.unshift({
      version: currentVersion.version,
      type: currentVersion.type,
      updateTime: currentVersion.updateTime,
      log: currentVersion.log || [],
    });
  }

  return {
    version: newVersion,
    type: versionType,
    updateTime: updateTime,
    log: log,
    historyVersion: historyVersion,
  };
};

// 保存版本信息
const saveVersion = (versionInfo) => {
  fs.writeFileSync(versionFile, JSON.stringify(versionInfo, null, 2));
};

// 获取更新日志
const getUpdateLog = async () => {
  console.log("\n请输入更新内容（每行一条，输入空行结束）：");
  const logs = [];

  while (true) {
    const log = await new Promise((resolve) => {
      rl.question("> ", resolve);
    });

    if (log.trim() === "") {
      break;
    }

    if (log.trim()) {
      logs.push(log.trim());
    }
  }

  return logs;
};

// 主函数
const main = async () => {
  // 直接选择更新类型
  console.log("请选择更新类型：");
  console.log("1. 大版本");
  console.log("2. 新特性功能");
  console.log("3. 修正bug");

  let type = await new Promise((resolve) => {
    rl.question("请选择(1/2/3): ", resolve);
  });

  // 校验输入
  while (!["1", "2", "3"].includes(type)) {
    type = await new Promise((resolve) => {
      rl.question("无效选择，请输入 1/2/3: ", resolve);
    });
  }

  try {
    const currentVersion = getCurrentVersion();
    // 逐行输入更新内容，空行结束，保存为数组
    const log = await getUpdateLog();
    const newVersion = updateVersion(currentVersion, type, log);
    saveVersion(newVersion);
    console.log(`\n版本已更新为: ${newVersion.version}`);
    console.log("更新内容:");
    if (log.length === 0) {
      console.log("(无)");
    } else {
      log.forEach((item, index) => {
        console.log(`${index + 1}. ${item}`);
      });
    }
  } catch (error) {
    console.error("更新版本失败:", error.message);
  }

  rl.close();
};

main();
